<?php


namespace App\Http\Controllers\Admin\Mall;


use App\Enums\MallEnum;
use App\Response\Response;
use Illuminate\Http\Request;
use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\BaseController;
//商品设置
class ProductSetController extends BaseController
{
     /**
      * @api {put} /mall/product/set-discount 设置折扣商品
      *
      * @apiGroup 个性商城-商品设置
      *
      * @apiParam {string} ids 商品id，多个用英文逗号隔开，必须
      * @apiParam {int} discount_rate 折扣值，1~99，80表示8折，以此类推，必须
      * @apiParam {int} discount_status 折扣状态，1：开启折扣；0：关闭折扣，必须
      *
      * @apiSuccessExample {json} Response-Example
      * {"code":200,"data":[],"message":""}
      */
    public function setDiscount(Request $request)
    {
        $param = $request->only('ids', 'discount_rate', 'discount_status');
        $v = app('validator')->make($param, [
            'ids' => 'required',
            'discount_rate' => 'required|integer|min:1|max:99',
            'discount_status' => 'required|integer|in:1,0',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $ids = array_reverse(explode(',', $param['ids']));
        $discountRate = $param['discount_rate'];
        $discountStatus = $param['discount_status'];

        //查询所有打折商品中最大的排序号
        $maxDiscountSort = app('model_mall_products')->where('discount_rate', '<', 100)->max('discount_sort');
        if (empty($maxDiscountSort)) $maxDiscountSort = 0;

        DB::beginTransaction();
        try {
            foreach ($ids as $k => $id) {
                $product = app('model_mall_products')
                    ->select('id', 'title', 'is_buyable', 'discount_rate', 'is_recommend')
                    ->where('id', $id)->first();
                if ($product) {
                    if ($product->is_buyable == 0) throw new BasicException(0, '可购买的商品才能设置折扣');
                    if ($product->is_recommend == 1) throw new BasicException(0, '设为推荐的商品不能设置打折，请先取消推荐。商品名称：' . $product->title);
                    //如果是新打折的商品将折扣排序号设置成最大，app端将排在最前
                    if ($product->discount_rate == 100) {
                        $product->discount_sort = $maxDiscountSort + $k + 2;
                    }
                    //设置折扣值和状态
                    $product->discount_rate = $discountRate;
                    $product->discount_status = $discountStatus;
                    $product->save();

                } else {
                    throw new BasicException(0, '商品id错误');
                }
            }

            DB::commit();
            return Response::sendData([]);
        } catch (\Exception $e) {
            throw new BasicException(0, $e->getMessage());
        }
    }

    /**
     * @api {put} /mall/product/cancel-discount 取消折扣商品
     *
     * @apiGroup 个性商城-商品设置
     *
     * @apiParam {string} ids 商品id，多个之间用英文逗号隔开，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[],"message":""}
     */
    public function cancelDiscount(Request $request)
    {
        $param = $request->only('ids', 'discount_rate');
        $v = app('validator')->make($param, [
            'ids' => 'required',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $ids = explode(',', $param['ids']);

        $res = app('model_mall_products')->whereIn('id', $ids)->update([
            'discount_rate' => 100,
            'discount_status' => 0,
            'discount_sort' => 0,
        ]);
        if ($res) {
            return Response::sendData([]);
        }
        throw new BasicException(0, '取消失败');
    }

    /**
     * @api {put} /mall/product/set-discount-status 设置折扣状态
     *
     * @apiGroup 个性商城-商品设置
     *
     * @apiParam {int} discount_status 折扣状态，1：开启折扣；0：关闭折扣，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[],"message":""}
     */
    public function setDiscountStatus(Request $request)
    {
        $param = $request->only('discount_status');
        $v = app('validator')->make($param, [
            'discount_status' => 'required|integer|in:1,0',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $discountStatus = $param['discount_status'];

        $where = [['discount_rate', '<', 100]];

        app('model_mall_products')->where($where)->update(['discount_status' => $discountStatus]);
        return Response::sendData([]);
    }

    /**
     * @api {get} /mall/product/get-discount-time 获取折扣时间
     *
     * @apiGroup 个性商城-商品设置
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "start_time": "2021-10-29 12:12:12", 开始时间
    "end_time": "2021-11-29 14:12:12" 结束时间
    },
    "message": ""
    }
     */
    public function getDiscountTime()
    {
        $key = 'MALL_PRODUCT_DISCOUNT';
        $config = app('model_config')->select('id', 'value')->where('key', $key)->first();
        if ($config) {
            return Response::sendData(json_decode($config->value));
        } else {
            return Response::sendData(['start_time' => '', 'end_time' => '']);
        }
    }

    /**
     * @api {put} /mall/product/set-discount-time 设置折扣时间
     *
     * @apiGroup 个性商城-商品设置
     *
     * @apiParam {string} discount_start_time 折扣开始时间，必须
     * @apiParam {string} discount_end_time 折扣结束时间，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[],"message":""}
     */
    public function setDiscountTime(Request $request)
    {
        $param = $request->only('discount_start_time', 'discount_end_time');
        $v = app('validator')->make($param, [
            'discount_start_time' => 'required|date_format:Y-m-d H:i:s',
            'discount_end_time' => 'required|date_format:Y-m-d H:i:s|after:discount_start_time',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $discountStartTime = $param['discount_start_time'];
        $discountEndTime = $param['discount_end_time'];

        $key = 'MALL_PRODUCT_DISCOUNT';
        $config = app('model_config')->select('id', 'value')->where('key', $key)->first();
        $data = ['value' => json_encode(['start_time' => $discountStartTime, 'end_time' => $discountEndTime])];
        if ($config) {
            app('model_config')->where('id', $config->id)->update($data);
        } else {
            $data['key'] = $key;
            $data['type'] = 1;
            $data['group'] = 100;
            $data['name'] = '商品折扣配置';
            app('model_config')->insert($data);
        }
        return Response::sendData([]);
    }

    /**
     * @api {put} /mall/product/set-recommend 设置或取消推荐商品
     *
     * @apiGroup 个性商城-商品设置
     *
     * @apiParam {int} id 商品id，必须
     * @apiParam {int} sort 排序号，默认100，升序排列
     * @apiParam {int} is_recommend 是否推荐，1：推荐；0：取消推荐，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[],"message":""}
     */
    public function setRecommend(Request $request)
    {
        $param = $request->only('id', 'is_recommend', 'sort');
        $v = app('validator')->make($param, [
            'id' => 'required',
            'is_recommend' => 'required|integer|in:0,1',
            'sort' => 'required_if:is_recommend,1|integer|min:0|max:65535',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $id = $param['id'];
        $sort = $param['sort'] ?? 100;
        $isRecommend = $param['is_recommend'];

        $product = app('model_mall_products')
            ->select('id', 'is_recommend', 'category_id', 'discount_rate', 'on_sale')
            ->where('id', $id)
            ->first();
        if ($product) {

            if ($product->on_sale == 2) throw new BasicException(0, '已下架的商品无法设置推荐或取消');
            if ($product->discount_rate < 100) throw new BasicException(0, '折扣商品无法设置为推荐商品');

            if ($isRecommend == 1) {
                if ($product->is_recommend == 1) throw new BasicException(0, '已是推荐商品，请勿重复设置');
            } else {
                if ($product->is_recommend == 0) throw new BasicException(0, '已是非推荐商品，不存在取消');
            }

            switch ($product->category_id) {
                case MallEnum::PRODUCT_CATE_ID_AVATAR:
                    $countLimit = 4;
                    $count = app('model_mall_products')->getRecommendCountByCategoryId(MallEnum::PRODUCT_CATE_ID_AVATAR);
                    if ($isRecommend == 1 && $count >= $countLimit) {
                        throw new BasicException(0, "头像框最多设置{$countLimit}个推荐");
                    }
                    break;
                case MallEnum::PRODUCT_CATE_ID_INTO_ROOM_SPECIAL:
                    $countLimit = 2;
                    $count = app('model_mall_products')->getRecommendCountByCategoryId(MallEnum::PRODUCT_CATE_ID_INTO_ROOM_SPECIAL);
                    if ($isRecommend == 1 && $count >= $countLimit) {
                        throw new BasicException(0, "入场特效最多设置{$countLimit}个推荐");
                    }
                    break;
                default:
                    if ($isRecommend == 1) {
                        throw new BasicException(0, '只有头像框或入场特效可以设置推荐');
                    }
            }

            $product->is_recommend = $isRecommend;
            $product->sort = $sort;
            $product->save();
            return Response::sendData([]);
        } else {
            throw new BasicException(0, '商品id错误');
        }
    }

}